<template>
  <div class="app-container bg-gray">
    <transition name="fade-transform" mode="out-in">
      <router-view/>
    </transition>
    <el-card v-if="isShow" class="box-1">
      <div class="header">
        <el-select v-model="searchTerms.branch_id" placeholder="团队" class="select" clearable @change="getData">
          <el-option v-for="item in branchList" :key="item.id" :label="item.branch_name" :value="item.id"/>
        </el-select>
        <!--无离职人员-->
        <!--<el-select v-model="searchTerms.user_id" placeholder="负责人" class="select" filterable clearable
                   @change="getData">
          <el-option v-for="item in usersList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>-->
        <!--有离职人员-->
        <el-select v-model="searchTerms.user_id" placeholder="负责人" class="select" filterable clearable @change="getData">
          <el-option-group
            v-for="group in allMemberList"
            :key="group.label"
            :label="group.label">
            <el-option
              v-for="item in group['personnel']"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-option-group>
        </el-select>
        <el-select v-model="searchTerms.surplus_time" placeholder="售后剩余时间" class="select" clearable
                   @change="getData">
          <el-option v-for="item in lastTimeList" :key="item.id" :label="item.label" :value="item.id"/>
        </el-select>
        <el-select v-model="searchTerms.status" placeholder="状态" class="select" clearable @change="getData">
          <el-option v-for="item in statusList" :key="item.id" :label="item.label" :value="item.id"/>
        </el-select>
        <el-date-picker
          v-model="searchTerms.date"
          :editable="false"
          class="picker"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="getData"/>
        <el-input v-model="searchTerms.searchValue" placeholder="客户名,手机,商品名,订单号" class="search-input"
                  @change="getData"/>
        <el-button type="success" class="do-btn" icon="el-icon-search" @click="currentPage=1, getData()">搜索</el-button>
        <el-button v-if="queryMatch(95)" type="success" class="bg-green" icon="el-icon-plus"
                   @click="toModify('售后订单-创建')">添加
        </el-button>
        <el-button v-if="queryMatch(116)" type="danger" icon="el-icon-share" @click="dialogVisible=true">转移
        </el-button>
        <span class="flex-1"/>
        <column-controller :check-items="th" @change="columnCheck"/>
      </div>
      <el-table v-loading="tableLoading" :data="tableData" :max-height="tableMaxHeight" border highlight-current-row
                @sort-change="handleSortChange" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" header-align="center" align="center"/>
        <el-table-column v-if="th[0].check" prop="goods_name" label="商品名称" min-width="160" header-align="center"
                         align="center"/>
        <el-table-column v-if="th[1].check" prop="after_name" label="负责人" min-width="80" header-align="center"
                         align="center"/>
        <el-table-column prop="number_sn" label="业绩订单号" min-width="160" header-align="center" align="center"/>
        <el-table-column v-if="th[2].check" prop="order_number" label="订单号" min-width="140" header-align="center"
                         align="center"/>
        <el-table-column v-if="th[3].check" prop="member_name" label="客户名称" min-width="120" header-align="center"
                         align="center"/>
        <el-table-column v-if="th[4].check" prop="member_phone" label="手机" min-width="120" header-align="center"
                         align="center"/>
        <el-table-column v-if="th[5].check" prop="goods_money" label="商品金额" min-width="120" header-align="center"
                         align="center" sortable/>
        <el-table-column v-if="th[7].check" prop="buy_time" label="购买时间" min-width="120" header-align="center"
                         align="center" sortable>
          <template slot-scope="scope">
            {{ parseTime(scope.row.buy_time, '{y}-{m}-{d}') }}
          </template>
        </el-table-column>
        <el-table-column v-if="th[8].check" prop="after_time" label="剩余售后时间(月)" min-width="135" header-align="center"
                         align="center">
          <template slot-scope="scope">
            {{ (scope.row.buy_length-scope.row.after_time) + ' / ' + scope.row.buy_length }}
          </template>
        </el-table-column>
        <el-table-column prop="bonus_royalty" label="预期奖金" min-width="100" header-align="center" align="center"/>
        <el-table-column prop="shift_status " label="类型" min-width="100" header-align="center" align="center" fixed="right">
          <template slot-scope="scope">
            {{ scope.row.shift_status===0?'默认':scope.row.shift_status===1?'转出':'转入' }}
          </template>
        </el-table-column>
        <el-table-column v-if="th[10].check" prop="after_status" label="状态" min-width="100" header-align="center" align="center" fixed="right">
          <template slot-scope="scope">
            <div @click="queryMatch(96)?toProhibit(scope.row):''">
              <el-tag v-if="scope.row.after_status===0" type="success">进行中</el-tag>
              <el-tag v-if="scope.row.after_status===1" type="info">已结束</el-tag>
              <el-tag v-if="scope.row.after_status===2" type="primary">待接收</el-tag>
              <el-tag v-if="scope.row.after_status===3" type="warning">待审核</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="200" header-align="center" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" size="small" icon="el-icon-search" circle @click="toModify('售后订单-详情',scope.row)"/>
            <el-tooltip :content="scope.row.after_status===2?'沟通并接收':'沟通'" placement="top">
              <el-button type="warning" size="small" icon="el-icon-service" circle @click="toAfterSaleDetails(scope.row, 1)"/>
            </el-tooltip>
            <el-tooltip v-if="queryMatch(265)&&scope.row.after_status===3" content="售后订单接收审核" placement="top">
              <span style="margin-left: 10px;">
                <el-button type="success" size="small" icon="el-icon-check" circle class="bg-green" @click="setStatus(scope.row, true)"/>
                <el-button type="danger" size="small" icon="el-icon-close" circle @click="setStatus(scope.row, false)"/>
              </span>
            </el-tooltip>
            <!--<el-button v-if="queryMatch(96)" type="success" size="small" icon="el-icon-edit" circle class="bg-green"
                       @click="toModify('售后订单-编辑',scope.row)"/>
            <el-button v-if="scope.row.after_status!==0&&queryMatch(97)" type="danger" size="small"
                       icon="el-icon-delete" circle @click="toDelete(scope.row)"/>-->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page.sync="currentPage"
        :page-size="pageSize"
        :page-sizes="pageSizes"
        :total="total"
        class="pagination"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"/>
    </el-card>

    <el-dialog :visible.sync="dialogVisible" title="订单转移" width="360px" class="dialog" center>
      <div class="content">
        <div class="text">将所选 {{ multipleSelection.length }} 条售后订单转移至</div>
        <el-select v-model="transfer.exchange_user" placeholder="请选择转移用户" filterable>
          <el-option v-for="item in usersList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :disabled="loading" :loading="loading" type="primary" @click="toTransfer">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {ColumnController} from '../../components'
  import {handleSortChange, handleSizeChange, handleCurrentChange, columnCheck, parseTime} from '@/utils/table'

  export default {
    components: {ColumnController},
    data() {
      return {
        isShow: false,
        loading: false,
        searchTerms: {
          branch_id: '',
          user_id: '',
          status: '',
          date: [],
          surplus_time: '',
          searchValue: ''
        },

        branchList: [], // 团队列表
        usersList: [], // 提交人列表
        allMemberList: [], // 所有人员列表
        statusList: [{id: 0, label: '进行中'}, {id: 1, label: '已结束'}], // 状态列表
        lastTimeList: [],

        dialogVisible: false,
        transfer: {
          exchange_user: '',
          exchange_list: ''
        },

        bonus_money: '',
        percentage_money: '',
        // 表格相关数据
        tableMaxHeight: document.documentElement.clientHeight - 380,
        tableLoading: false,
        multipleSelection: [],
        currentPage: 1,
        pageSize: this.$store.getters.userInfo.pageSize,
        pageSizes: [10, 20, 50, 100, 1000],
        total: 0,
        tableData: [],
        th: [{name: '商品名称', check: true},
          {name: '负责人', check: true},
          {name: '订单号', check: true},
          {name: '客户名称', check: true},
          {name: '客户手机', check: true},
          {name: '商品售价', check: true},
          {name: '售后提成', check: true},
          {name: '购买时间', check: true},
          {name: '售后时间(月)', check: true},
          {name: '剩余提成', check: true},
          {name: '订单状态', check: true}]
      }
    },
    watch: {
      $route(to) {
        if (to.name === '售后订单') {
          this.getData()
          setTimeout(() => {
            this.isShow = true
          }, 500)
        } else {
          this.isShow = false
        }
      }
    },
    created() {
      if (this.$route.name === '售后订单') {
        this.isShow = true
        this.getData()
        this.getBranchList()
        this.getUsersList();
        this.getAllMemberList();
        for (let i = 1; i < 26; i++) {
          i < 25 && this.lastTimeList.push({id: i, label: i + '个月'})
          i === 25 && this.lastTimeList.push({id: i, label: '两年以上'})
        }
      }
    },
    methods: {
      handleCurrentChange, handleSizeChange, handleSortChange, columnCheck, parseTime,
      getData(order) {
        this.tableLoading = true
        order || (order = {})
        const url = 'aftersale/list'
        const data = {
          page_no: this.currentPage,
          page_size: this.pageSize,
          search: this.searchTerms.searchValue,
          branch_id: this.searchTerms.branch_id,
          status: this.searchTerms.status,
          user_id: this.searchTerms.user_id,
          surplus_time: this.searchTerms.surplus_time
        }
        this.searchTerms.date && this.searchTerms.date.length !== 0 && (data.start_time = this.searchTerms.date[0] + ' 00:00:00', data.end_time = this.searchTerms.date[1] + ' 23:59:59')
        order.sortName && (data.sortName = order.sortName)
        order.sortOrder && (data.sortOrder = order.sortOrder)
        this.$store.dispatch('GetConnect', {url, data}).then(res => {
          this.tableData = res.data.rows
          this.percentage_money = res.data.percentage_money
          this.bonus_money = res.data.bonus_money
          this.total = res.data.total;
          this.tableLoading = false;
        }).catch(e => {
          this.tableLoading = false;
          this.$message.error(e.msg + ',请刷新或联系管理员');
        })
      },

      /**
       *  获取团队列表
       *  接口:'branch/all-list'
       */
      getBranchList() {
        const url = 'branch/all-list'
        this.$store.dispatch('GetConnect', {url}).then(res => {
          this.branchList = res.data
        }).catch(e => {
          this.$message.error(e.msg + ',请刷新或联系管理员')
        })
      },

      /**
       *  获取系统用户列表
       *  接口:'user/all-list'
       */
      getUsersList() {
        const url = 'user/all-list'
        this.$store.dispatch('GetConnect', {url}).then(res => {
          this.usersList = res.data
        }).catch(e => {
          this.$message.error(e.msg + ',请刷新或联系管理员')
        })
      },

      /**
       *  获取全部用户列表
       *  接口:'user/admin-list'
       */
      getAllMemberList() {
        const url = 'user/admin-list'
        this.$store.dispatch('GetConnect', {url}).then(res => {
          this.allMemberList = res.data.list
        }).catch(e => {
          this.$message.error(e.msg + ',请刷新或联系管理员')
        })
      },

      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },

      toTransfer() {
        this.$confirm('此操作将转移该售后订单, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const url = 'aftersale/exchangeOrder'
          const data = {
            exchange_user: this.transfer.exchange_user,
            exchange_list: []
          }
          const temp = []
          for (const i in this.multipleSelection) {
            temp.push(this.multipleSelection[i].id)
          }
          data.exchange_list = JSON.stringify(temp)
          this.loading = true;
          this.$store.dispatch('GetConnect', {url, data}).then(res => {
            this.$message.success(res.msg)
            this.getData()
            this.dialogVisible = false
            this.loading = false;
          }).catch(e => {
            this.$message.error(e.msg + ',请刷新或联系管理员')
            this.dialogVisible = false
            this.loading = false
          })
        })
      },
      toModify(title, row) {
        this.isShow = false
        const query = {title: title}
        row && (query.id = row.id)
        this.$router.push({
          path: '/orders/afterSale/modify',
          query: query
        })
      },
      // 启用禁用
      toProhibit(row) {
        this.$confirm('此操作将结束该售后订单, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const url = 'aftersale/ajax/' + row.id + '?action=prohibit'
          this.$store.dispatch('GetConnect', { url }).then(res => {
            row.after_status !== 1 ? (row.after_status = 1) : ''
          }).catch(e => {
            this.$message.error(e.msg + ',请刷新或联系管理员')
          })
        })
      },
      toDelete(row) {
        this.$confirm('此操作将删除该售后订单, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const url = 'aftersale/delete/' + row.id
          this.$store.dispatch('GetConnect', {url}).then(res => {
            this.$message.success('删除成功！')
            this.getData()
          }).catch(e => {
            this.$message.error(e.msg + ',请刷新或联系管理员')
          })
        })
      },

      toAfterSaleDetails(row, type) {
        this.isShow = false;
        const query = {
          id: row.member_id,
          type: type
        };
        this.$router.push({
          path: '/user/afterSales/details',
          query: query
        });
      },
      setStatus(row, status) {
        this.$confirm('此操作将' + (status ? '同意' : '拒绝') + '该售后转移, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const url = 'aftersale/verifyOrder';
          const data = {
            id: row.id,
            status: status ? 'agree' : 'refuse'
          }
          this.$store.dispatch('GetConnect', { url, data }).then(res => {
            this.$message.success(res.msg)
            this.getData()
          }).catch(e => {
            this.$message.error(e.msg + ',请刷新或联系管理员')
          })
        })
      }
    }
  }
</script>

<style lang="scss" type="text/scss" scoped>
  @import '../../../styles/index.scss';
  .box-1 {
    .header {
      @include flex-row(center, flex-start);
      padding: 2px 0;
      flex-wrap: wrap;
      .select {
        padding-right: 15px;
        width: 160px;
      }
      .picker {
        margin-right: 15px;
        width: 300px;
      }
      .do-btn {
        @extend .bg-green;
        margin-left: 6px;
      }
      .search-input {
        width: 240px;
      }
    }
  }
  .dialog {
    .content {
      text-align: center;
      .text {
        padding-bottom: 20px;
      }
    }
  }
  .el-tag {
    cursor: pointer;
  }
</style>

